package com.bootdo.common.utils;

import java.math.BigDecimal;

/**
 * @Author: hje
 * @Description:
 * @Date: 2019/5/19 上午12:17
 */
public class MoneyConvert {
    //分转换为元，返回string类型
    public static String centToDollarForString(Object t){
        if (t == null) {
            return "0";
        } else {
            BigDecimal amount = getBigDecimal(t);
            amount = amount.divide(new BigDecimal(100));
            return amount.toString();
        }
    }

    //分转换为元，返回double类型
    public static Double centToDollarForDouble(Object t){
        if (t == null) {
            return 0D;
        } else {
            BigDecimal amount = getBigDecimal(t);
            amount = amount.divide(new BigDecimal(100));
            return amount.doubleValue();
        }
    }

    // 元转换为分
    public static Long DollarToCentForLong(Object t){
        if (t == null) {
            return 0L;
        } else {
            BigDecimal amount = getBigDecimal(t);
            amount = amount.multiply(new BigDecimal(100));
            return amount.longValue();
        }
    }

    private static BigDecimal getBigDecimal(Object t) {
        BigDecimal amount;
        if(t instanceof Integer){
            amount = new BigDecimal(t.toString());
        }
        else if(t instanceof Long){
            amount = new BigDecimal(t.toString());
        }
        else if(t instanceof String){
            amount=new BigDecimal(t.toString());
        }
        else{
            throw new RuntimeException(String.format("不支持的数据类型,%s",t.getClass()));
        }
        return amount;
    }
}
